package com.ikingtech.framework.sdk.data.mybatisplus.helper;

import com.ikingtech.framework.sdk.data.mybatisplus.entity.SortEntity;
import com.ikingtech.framework.sdk.utils.Tools;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tie yan
 */
public class LevelCrossDragHelper<T extends SortEntity> extends AbstractDragHelper<T>{
    @Override
    public List<T> drag() {
        T currentNode = this.currentNode.get();
        List<T> sortedEntities = new ArrayList<>();
        T targetNode = this.targetNode.get();
        currentNode.setParentId(targetNode.getParentId());
        currentNode.setSortOrder(Boolean.TRUE.equals(this.beforeTarget) ? targetNode.getSortOrder() : targetNode.getSortOrder() + 1);
        currentNode.setFullPath(Tools.Str.format("{}@{}", this.targetParentNodeFullPath.get(), currentNode.getId()));
        targetNode.setSortOrder(Boolean.TRUE.equals(this.beforeTarget) ? targetNode.getSortOrder() + 1 : targetNode.getSortOrder());
        sortedEntities.addAll(Tools.Coll.traverse(this.nodeAfterCurrent.get(), entity -> {
            entity.setSortOrder(entity.getSortOrder() - 1);
            return entity;
        }));
        sortedEntities.addAll(Tools.Coll.convertList(this.nodeAfterTarget.get(), entity -> {
            entity.setSortOrder(entity.getSortOrder() + 1);
            return entity;
        }));
        sortedEntities.add(currentNode);
        sortedEntities.add(targetNode);
        return sortedEntities;
    }
}
